package com.alvis.exam.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.alvis.exam.base.BaseApiController;
import com.alvis.exam.base.RestResponse;
import com.alvis.exam.listener.StationDictListener;
import com.alvis.exam.service.StationService;
import com.alvis.exam.viewmodel.admin.station.StationDictExcelVM;
import com.alvis.exam.viewmodel.admin.station.StationDictPageRequestVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/api/admin/station")
@Validated
public class StationController extends BaseApiController {

    @Autowired
    private StationService service;

    @PostMapping("/page")
    public Object page(@RequestBody StationDictPageRequestVM model) {
        return RestResponse.okList(service.querySelective(model));
    }

    @PostMapping("/upload")
    public Object create(MultipartFile file) {
        service.deleteAll();
        try (InputStream io = file.getInputStream()) {
            EasyExcel.read(io, StationDictExcelVM.class, new StationDictListener(service)).sheet().doRead();
        } catch (IOException e) {
            return RestResponse.fail(-1, e.getMessage());
        }
        return RestResponse.ok();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        service.deleteById(id);
        return RestResponse.ok();
    }
}
